package com.neu.controller;

import com.neu.base.Result;
import com.neu.entity.FpFatherDemand;
import com.neu.entity.FpSecondDemand;
import com.neu.entity.Task;
import com.neu.service.FpFatherDemandService;
import com.neu.service.FpSecondDemandService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.neu.entity.dto.DemandDTO;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @author 17478
 * @ClassName: FpSecondDemandCon
 * @description: TODO
 * @date 2024-11-18 15:03
 * @version: 1.0
 */
@Api(tags = "子级需求管理")
@RestController
@RequestMapping("/second-demand")
public class FpSecondDemandController {

    @Autowired
    private FpSecondDemandService fpSecondDemandService;
    @Autowired
    private FpFatherDemandService fpFatherDemandService;

    // 查询所有子级需求并返回父级需求关联信息
    @GetMapping("/list")
    @ApiOperation("查询所有二级需求")
    public Result<List<DemandDTO>> listDemand() {
        List<DemandDTO> demandList = fpSecondDemandService.listDemand();
        return Result.success(demandList);
    }

    @GetMapping("/listByTaskId")
    @ApiOperation("根据任务id查找对应需求")
    public Result<List<DemandDTO>> listByTaskId(@RequestParam("taskId") String taskId) {
        List<DemandDTO> demand = fpSecondDemandService.listByTaskId(taskId);
        return Result.success(demand);
    }

    // 添加子级需求
    @PostMapping("/add")
    @ApiOperation("添加子级需求")
    public Result<?> add(@RequestBody FpSecondDemand fpSecondDemand) {
        fpSecondDemand.calufp();
        boolean isSaved = fpSecondDemandService.save(fpSecondDemand);
        return Result.success(isSaved);

    }

    // 修改子级需求
    @PutMapping("/update")
    @ApiOperation("修改子级需求")
    public Result<?> update(@RequestBody FpSecondDemand fpSecondDemand) {
        fpSecondDemand.calufp();
        boolean isUpdated = fpSecondDemandService.updateById(fpSecondDemand);
//        if (isUpdated) {
        return Result.success(isUpdated);
//        }
//        return Result.error("子级需求修改失败");
    }

    // 删除单个子级需求
    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除子级需求")
    public Result<?> delete(@PathVariable("id") int id) {
        boolean isDeleted = fpSecondDemandService.removeById(id);
//        if (isDeleted) {
        return Result.success(isDeleted);
//        }
//        return Result.error("子级需求删除失败");
    }

    // 批量删除子级需求
    @DeleteMapping("/batch-delete")
    @ApiOperation("批量删除子级需求")
    public Result<?> batchDelete(@RequestBody List<Integer> ids) {
        boolean isDeleted = fpSecondDemandService.removeByIds(ids);
//        if (isDeleted) {
        return Result.success(isDeleted);
//        }
//        return Result.error("批量删除失败");
    }

    // 根据子级需求名称查询
    @GetMapping("/search-by-name")
    @ApiOperation("根据子级需求名称查询")
    public Result<List<DemandDTO>> searchByName(@RequestParam("name") String name) {
        List<FpSecondDemand> result = fpSecondDemandService.lambdaQuery()
                .like(FpSecondDemand::getSname, name)
                .list();

        List<DemandDTO> demandDTOList = result.stream()
                .map(secondDemand -> {
                    FpFatherDemand fatherDemand = fpFatherDemandService.getById(secondDemand.getFid());
                    return new DemandDTO(
                            secondDemand.getSid(),
                            secondDemand.getFid(),
                            fatherDemand != null ? fatherDemand.getPname() : null,
                            secondDemand.getSname(),
                            secondDemand.getDescription(),
                            secondDemand.getType(),
                            secondDemand.getUfp(),
                            secondDemand.getDegree()
                    );
                })
                .collect(Collectors.toList());

        return Result.success(demandDTOList);
    }

    // 根据子级需求描述查询
    @GetMapping("/search-by-description")
    @ApiOperation("根据子级需求描述查询")
    public Result<List<DemandDTO>> searchByDescription(@RequestParam("description") String description) {
        List<FpSecondDemand> result = fpSecondDemandService.lambdaQuery()
                .like(FpSecondDemand::getDescription, description)
                .list();

        List<DemandDTO> demandDTOList = result.stream()
                .map(secondDemand -> {
                    FpFatherDemand fatherDemand = fpFatherDemandService.getById(secondDemand.getFid());
                    return new DemandDTO(
                            secondDemand.getSid(),
                            secondDemand.getFid(),
                            fatherDemand != null ? fatherDemand.getPname() : null,
                            secondDemand.getSname(),
                            secondDemand.getDescription(),
                            secondDemand.getType(),
                            secondDemand.getUfp(),
                            secondDemand.getDegree()
                    );
                })
                .collect(Collectors.toList());

        return Result.success(demandDTOList);
    }

    // 根据子级需求功能点类型查询
    @GetMapping("/search-by-type")
    @ApiOperation("根据子级需求功能点类型查询")
    public Result<List<DemandDTO>> searchByType(@RequestParam("type") String type) {
        List<FpSecondDemand> result = fpSecondDemandService.lambdaQuery()
                .eq(FpSecondDemand::getType, type)
                .list();

        List<DemandDTO> demandDTOList = result.stream()
                .map(secondDemand -> {
                    FpFatherDemand fatherDemand = fpFatherDemandService.getById(secondDemand.getFid());
                    return new DemandDTO(
                            secondDemand.getSid(),
                            secondDemand.getFid(),
                            fatherDemand != null ? fatherDemand.getPname() : null,
                            secondDemand.getSname(),
                            secondDemand.getDescription(),
                            secondDemand.getType(),
                            secondDemand.getUfp(),
                            secondDemand.getDegree()
                    );
                })
                .collect(Collectors.toList());

        return Result.success(demandDTOList);
    }


    // 新增父级和子级需求
    @PostMapping("/add-with-parent")
    @ApiOperation("新增父级和子级需求")
    public Result<?> addWithParent(@RequestBody DemandDTO demandDTO) {
        boolean isAdded = fpSecondDemandService.addWithParent(demandDTO);
//        if (isAdded) {
        return Result.success(isAdded);
//        }
//        return Result.error("父级和子级需求新增失败");
    }

    @GetMapping("/search-by-pname")
    @ApiOperation("根据父级需求名称查询")
    public Result<List<DemandDTO>> searchByPname(@RequestParam("pname") String pname) {
        // 根据父级需求名称查询所有父级需求
        List<FpFatherDemand> fatherDemands = fpFatherDemandService.lambdaQuery()
                .like(FpFatherDemand::getPname, pname)
                .list();

        // 如果没有找到匹配的父级需求，直接返回空结果
        if (fatherDemands.isEmpty()) {
            return Result.success(Collections.emptyList());
        }

        // 构建父级需求的映射表（fid -> FpFatherDemand）
        Map<Integer, FpFatherDemand> fatherDemandMap = fatherDemands.stream()
                .collect(Collectors.toMap(FpFatherDemand::getId, fatherDemand -> fatherDemand));

        // 获取所有父级需求的 ID 列表
        List<Integer> fatherIds = new ArrayList<>(fatherDemandMap.keySet());

        // 查询与这些父级需求 ID 关联的所有子级需求
        List<FpSecondDemand> secondDemands = fpSecondDemandService.lambdaQuery()
                .in(FpSecondDemand::getFid, fatherIds)
                .list();

        // 转换为 DTO 格式
        List<DemandDTO> demandDTOList = secondDemands.stream()
                .map(secondDemand -> {
                    FpFatherDemand fatherDemand = fatherDemandMap.get(secondDemand.getFid());

                    return new DemandDTO(
                            secondDemand.getSid(),
                            secondDemand.getFid(),
                            fatherDemand != null ? fatherDemand.getPname() : null,
                            secondDemand.getSname(),
                            secondDemand.getDescription(),
                            secondDemand.getType(),
                            secondDemand.getUfp(),
                            secondDemand.getDegree()
                    );
                })
                .collect(Collectors.toList());

        return Result.success(demandDTOList);
    }

    @GetMapping("/allForFp")
    @Operation(summary = "获取功能点评估任务")
    public Result allForFp() {
        List<Task> tasks = fpSecondDemandService.allForFp();
        return Result.success(tasks);
    }


    @PostMapping("/cauclTotalUfp")
    public Result listDemandByTaskId(@RequestParam String taskId) {
        return fpSecondDemandService.cauclTotalUfp(taskId);
    }

}

//@Api(tags = "子级需求管理")
//@RestController
//@RequestMapping("/second-demand")
//public class FpSecondDemandController {
//
//    @Autowired
//    private FpSecondDemandService fpSecondDemandService;
//
//    // 查询所有子级需求并返回父级需求关联信息
//    @GetMapping("/list")
//    @ApiOperation("查询所有二级需求")
//    public Result<List<DemandDTO>> listDemand() {
//        // 调用服务层方法获取二级需求与父级需求的联合数据
//        List<DemandDTO> demandList = fpSecondDemandService.listDemand();
//
//        // 返回成功结果并封装数据
//        return Result.success(demandList);
//    }
//
//    // 添加子级需求
//    @PostMapping("/add")
//    @ApiOperation("添加子级需求")
//    public Result<?> add(@RequestBody FpSecondDemand fpSecondDemand) {
//        boolean isSaved = fpSecondDemandService.save(fpSecondDemand);
//        if (isSaved) {
//            return Result.success("子级需求添加成功");
//        }
//        return Result.error("子级需求添加失败");
//    }
//
//    // 修改子级需求
//    @PutMapping("/update")
//    @ApiOperation("修改子级需求")
//    public Result<?> update(@RequestBody FpSecondDemand fpSecondDemand) {
//        boolean isUpdated = fpSecondDemandService.updateById(fpSecondDemand);
//        if (isUpdated) {
//            return Result.success("子级需求修改成功");
//        }
//        return Result.error("子级需求修改失败");
//    }
//
//    // 删除单个子级需求
//    @DeleteMapping("/delete/{id}")
//    @ApiOperation("删除子级需求")
//    public Result<?> delete(@PathVariable("id") int id) {
//        boolean isDeleted = fpSecondDemandService.removeById(id);
//        if (isDeleted) {
//            return Result.success("子级需求删除成功");
//        }
//        return Result.error("子级需求删除失败");
//    }
//
//    // 批量删除子级需求
//    @DeleteMapping("/batch-delete")
//    @ApiOperation("批量删除子级需求")
//    public Result<?> batchDelete(@RequestBody List<Integer> ids) {
//        boolean isDeleted = fpSecondDemandService.removeByIds(ids);
//        if (isDeleted) {
//            return Result.success("批量删除成功");
//        }
//        return Result.error("批量删除失败");
//    }
//
//    // 根据子级需求名称查询
//    @GetMapping("/search-by-name")
//    @ApiOperation("根据子级需求名称查询")
//    public Result<?> searchByName(@RequestParam("name") String name) {
//        List<FpSecondDemand> result = fpSecondDemandService.lambdaQuery()
//                .like(FpSecondDemand::getSname, name)
//                .list();
//        return Result.success(result);
//    }
//
//    // 根据子级需求描述查询
//    @GetMapping("/search-by-description")
//    @ApiOperation("根据子级需求描述查询")
//    public Result<?> searchByDescription(@RequestParam("description") String description) {
//        List<FpSecondDemand> result = fpSecondDemandService.lambdaQuery()
//                .like(FpSecondDemand::getDescription, description)
//                .list();
//        return Result.success(result);
//    }
//
//    // 根据子级需求功能点类型查询
//    @GetMapping("/search-by-type")
//    @ApiOperation("根据子级需求功能点类型查询")
//    public Result<?> searchByType(@RequestParam("type") String type) {
//        List<FpSecondDemand> result = fpSecondDemandService.lambdaQuery()
//                .eq(FpSecondDemand::getType, type)
//                .list();
//        return Result.success(result);
//    }
//}
//
